package com.example.newnoke.ui;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.LinearLayout;

import com.example.newnoke.APP;
import com.example.newnoke.MainActivity;
import com.example.newnoke.R;
import com.example.newnoke.utils.API;
import com.example.newnoke.utils.PrefUtils;
import com.example.newnoke.view.dialog.UPDataDialgo;
import com.geya.jbase.constant.RequestType;
import com.geya.jbase.uiview.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;


/**
 * Created by Administrator on 2016/5/19.
 * <p>
 * 欢迎界面Activity
 */
public class SplashActivity extends FragmentActivity {

    LinearLayout mLinearLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);
        applyJurisdiction();
        OkGo.<String>post(RequestType.ADDRESS + API.VERSION)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject object = new JSONObject(response.body());

                            if (object.optInt("code") == 200) {
                                JSONObject data = object.optJSONObject("android");
                                checkVersion(data.optString("version"), data.optString("content"), data.optString("url"));
                            } else {
                                init();
                                startAnim();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            ToastUtil.showShort("数据解析异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        ToastUtil.showShort("");
                                init();
        startAnim();
                    }
                });
//        init();
//        startAnim();
    }


    public void init() {
        mLinearLayout = (LinearLayout) findViewById(R.id.splash_ll);
    }

    /**
     * 启动动画的方法
     */
    private void startAnim() {
        //动画效果同事进行创建
        AnimationSet set = new AnimationSet(false);

        // 创建旋转动画 懂0的位置开始 旋转360度 自身旋转 0.5f（基于zhongxindian）
//        RotateAnimation rotatr = newss RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f,
//                Animation.RELATIVE_TO_SELF, 0.5f);
//        rotatr.setDuration(1000);// 动画时间
//        rotatr.setFillAfter(true);// 保存动画完成后的状态

        // 创建缩放动画
        ScaleAnimation scakle = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        scakle.setDuration(700);// 动画时间
        scakle.setFillAfter(true);// 保存动画完成后的状态

        //创建渐变动画 从完全透明到不完全不透明
        AlphaAnimation alpha = new AlphaAnimation(1, 1);
        alpha.setDuration(1300);// 动画时间
        alpha.setFillAfter(true);// 保存动画完成后的状态

        //添加动画
//        set.addAnimation(rotatr);
//        set.addAnimation(scakle);
        set.addAnimation(alpha);

        //设置动画监听  动画完成后跳转到 引导界面 或 主页
        set.setAnimationListener(new Animation.AnimationListener() {


            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub

            }


            @Override
            public void onAnimationRepeat(Animation arg0) {

            }


            @Override
            public void onAnimationEnd(Animation arg0) {

                jumpNexPage();
//                startActivity(newss Intent(SplashActivity.this, MainActivity.class));//
                finish();
            }
        });

        //运行动画
        mLinearLayout.startAnimation(set);


    }


    /**
     * 页面跳转
     */
    private void jumpNexPage() {

        boolean userGuide = PrefUtils.getBoolean(this, "is_user_guide_showed", false);

        if (!userGuide) {
            PrefUtils.setBoolean(this, "is_user_guide_showed", true);
            startActivity(new Intent(SplashActivity.this, LoginActivity.class));
//            startActivity(new Intent(SplashActivity.this, GuideActivity.class));
        } else {
            if (APP.getUesrInfo() == null) {
                startActivity(new Intent(SplashActivity.this, LoginActivity.class));
            } else {
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
            }
        }
        finish();
    }


    private int getVersionCode() {
        PackageManager pm = getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException ignored) {
        }
        return 0;
    }

    /**
     * 申请权限
     */
    public void applyJurisdiction() {

        AndPermission.with(this)
                .requestCode(101)//
                .permission(Permission.STORAGE)//WRITE_EXTERNAL_STORAGE
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(SplashActivity.this, rationale).show();
                    }
                })
                .start();
    }


    private File mFile;

    private void checkVersion(String newVersion, String text, String url) {
        //TODO 版本检测 (新版增加下载进度显示)
//        File file2=getActivity().getExternalCacheDir();
//        System.out.println("---------------------- 安卓路径 " + file2.getPath());
        int code = Integer.parseInt(newVersion);
        int version = getVersionCode();


        if (code > version) {


            UPDataDialgo dialgo = new UPDataDialgo();

            Bundle bundle = new Bundle();
            bundle.putString("content", text);
            bundle.putString("url", url);
            dialgo.setArguments(bundle);
            dialgo.show(getSupportFragmentManager(), new UPDataDialgo.PayCallBack() {
                @Override
                public void installation(File file) {
                    // file 即为文件数据，文件保存在指定目录
                    mFile = file;
                    //兼容8.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        boolean hasInstallPermission = getPackageManager().canRequestPackageInstalls();
                        if (!hasInstallPermission) {
//                            ToastUtil.makeText(MyApplication.getContext(), MyApplication.getContext().getString(R.string.string_install_unknow_apk_note), false);
                            startInstallPermissionSettingActivity();
                            return;
                        }
                    }
                    checkIsAndroidO(mFile);
                }

                @Override
                public void onError(String msg) {

                    ToastUtil.showShort(msg.equals("") ? "下载失败" : msg);

                }
            });

        } else {
            init();
            startAnim();
        }


    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, REQUEST_CODE_UNKNOWN_APP);
    }

    /**
     * 判断是否是8.0,8.0需要处理未知应用来源权限问题,否则直接安装
     */
    private void checkIsAndroidO(File file) {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean canRequestPackageInstalls = getPackageManager().canRequestPackageInstalls();
            if (canRequestPackageInstalls) {
                openAPK(file);
            } else {
                //请求安装未知应用来源的权限
                openAPK(file);
//                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 10010);
            }
        } else {
            openAPK(file);
        }

    }

    /**
     * 打开apk
     */
    private void openAPK(File file) {
        try {
            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0 以上
                String authority = getApplicationContext().getPackageName() + ".fileProvider";
                Uri apkUri = FileProvider.getUriForFile(this, authority, file);//在AndroidManifest中的android:authorities值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                startActivity(install);
            } else {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(install);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final int REQUEST_CODE_UNKNOWN_APP = 2001;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10012:
//                String root = Environment.getExternalStorageDirectory().getPath();
//                File file = new File(root, "yaofenqi.apk");
                checkIsAndroidO(mFile);
                break;
            case REQUEST_CODE_UNKNOWN_APP:
                if (mFile != null) {
                    checkIsAndroidO(mFile);
                }
                break;
            default:
                break;
        }
    }


    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
//            switch (requestCode) {
//                case REQUEST_CODE_PERMISSION_SINGLE: {
//                    // TODO do something.
//                    Toast.makeText(ListenerActivity.this, R.string.successfully, Toast.LENGTH_SHORT).show();
//                    break;
//                }
//                case REQUEST_CODE_PERMISSION_MULTI: {
//                    // TODO do something.
//                    Toast.makeText(ListenerActivity.this, R.string.successfully, Toast.LENGTH_SHORT).show();
//                    break;
//                }
//            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
//            switch (requestCode) {
//                case REQUEST_CODE_PERMISSION_SINGLE: {
//                    // TODO The strategy after failure.
//                    Toast.makeText(ListenerActivity.this, R.string.failure, Toast.LENGTH_SHORT).show();
//                    break;
//                }
//                case REQUEST_CODE_PERMISSION_MULTI: {
//                    // TODO The strategy after failure.
//                    Toast.makeText(ListenerActivity.this, R.string.failure, Toast.LENGTH_SHORT).show();
//                    break;
//                }
//            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
//            if (AndPermission.hasAlwaysDeniedPermission(ListenerActivity.this, deniedPermissions)) {
//                // 第一种：用默认的提示语。
//                AndPermission.defaultSettingDialog(ListenerActivity.this, REQUEST_CODE_SETTING).show();
//
//                // 第二种：用自定义的提示语。
            AndPermission.defaultSettingDialog(SplashActivity.this)
                    .setTitle("权限申请失败")
                    .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                    .setPositiveButton("好，去设置")
                    .show();


////            第三种：自定义dialog样式。
////            SettingService settingService = AndPermission.defineSettingDialog(this, REQUEST_CODE_SETTING);
////            你的dialog点击了确定调用：
////            settingService.execute();
////            你的dialog点击了取消调用：
////            settingService.cancel();
//            }
        }
    };


}